package com.esyoga.yoyoga.configuration;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.esyoga.yoyoga.realm.UserRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;


@Configuration	//将当前类指定为配置类
public class ShiroConfiguration {
	
	//配置realm
	@Bean
	public UserRealm getRealm(){
		UserRealm realm = new UserRealm();
		System.out.println("创建realm:"+realm);
		return realm;
	}
	
	//安全管理器
	@Bean
	public DefaultWebSecurityManager getManager(UserRealm realm){
		System.out.println("manager:"+realm);
		DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
		manager.setRealm(realm);
		return manager;
	}
	
	//过滤器
	@Bean
	public ShiroFilterFactoryBean getFactoryBean(DefaultWebSecurityManager manager){
		System.out.println("创建shiro过滤器");
		ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
		bean.setSecurityManager(manager);
		//登陆页面
		bean.setLoginUrl("/index.html");
		//没有权限
		bean.setUnauthorizedUrl("/error/error.html");
		//过滤器链
		Map<String, String> map = new  LinkedHashMap<>();
		//map.put("/**","anon");
		map.put("/index.html", "anon");
		map.put("/user/login2", "anon");
		//druid放行
		map.put("/druid/**", "anon");
		//配置角色验证
		map.put("/student/**","roles[student]");
		map.put("/gym/**","roles[gym]");
		map.put("/trainer/**","roles[trainer]");
		map.put("/platform/**","roles[platform]");
		//静态资源放行
		map.put("/css/**", "anon");
		map.put("/fonts/**", "anon");
		map.put("/js/**", "anon");
		map.put("/images/**", "anon");
		// 配置退出过滤器
		map.put("/logout", "logout");
		bean.setFilterChainDefinitionMap(map);
		return bean;
	}
	//用户shiro和thymeleaf标签一起使用
	@Bean
	public ShiroDialect getShiroDialect(){
		return new ShiroDialect();
	}

	/*//手动设置一个加解密密钥
	@Bean
	public CookieRememberMeManager cookieRememberMeManager() {
		CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
		SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
		simpleCookie.setMaxAge(259200000);
		cookieRememberMeManager.setCookie(simpleCookie);
		cookieRememberMeManager.setCipherKey(Base64.decode("6ZmI6I2j5Y+R5aSn5ZOlAA=="));
		return cookieRememberMeManager;
	}*/
}
